package com.advert.presentation.tools;

import com.advert.dto.ModelSearchCriteria;
import com.advert.model.support.VehicleModelEntity;
import com.advert.model.vehicle.VehicleEntity;
import com.advert.presentation.util.EntityComparator;
import com.advert.service.support.SupportService;
import com.advert.util.Event;
import com.advert.presentation.util.localization.LabelsMap;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Name("vehicleModels")
@Scope(ScopeType.PAGE)
@AutoCreate
public class VehicleModelsManager implements Serializable {
    @In(value = "SupportService")
    private SupportService supportService;
    @In(value = "labels")
    private LabelsMap labelsMap;

    private ModelSearchCriteria searchCriteria;
    private Map<String, List<VehicleModelEntity>> modelsCache;


    @Observer(Event.VEHICLE_MODEL_REQUIRED)
    public void suggestedModel(VehicleEntity vehicle) {
        searchCriteria = new ModelSearchCriteria(vehicle.getTypeCode(), vehicle.getCategoryCode(), vehicle.getBrandId());
    }

    @Unwrap
    public List<VehicleModelEntity> getModels() {
        List<VehicleModelEntity> retVal = null;
        if (searchCriteria != null) {
            retVal = modelsCache.get(searchCriteria.toString());
            if (retVal == null) {
                retVal = supportService.searchVehicleModels(searchCriteria);
                Collections.sort(retVal, new EntityComparator(labelsMap));
                modelsCache.put(searchCriteria.toString(), retVal);
            }
        } else {
            retVal = modelsCache.get("");
        }
        return retVal;
    }

    @Create
    public void init() {
        modelsCache = new ConcurrentHashMap<String, List<VehicleModelEntity>>();
        modelsCache.put("", Collections.<VehicleModelEntity>emptyList());
    }
}
